const { Pet, User } = require('../models');
const { AppError } = require('../middleware/errorHandler');
const logger = require('../utils/logger');
const { validationResult } = require('express-validator');
const { Op } = require('sequelize');

// 过滤对象，只保留允许的字段
const filterObj = (obj, ...allowedFields) => {
  const newObj = {};
  Object.keys(obj).forEach(el => {
    if (allowedFields.includes(el)) newObj[el] = obj[el];
  });
  return newObj;
};

// 获取当前用户的所有宠物
exports.getMyPets = async (req, res, next) => {
  try {
    const pets = await Pet.findAll({
      where: { ownerId: req.user.id },
      order: [['createdAt', 'DESC']],
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'email']
      }]
    });
    
    res.status(200).json({
      status: 'success',
      results: pets.length,
      data: {
        pets
      }
    });
  } catch (error) {
    logger.error('获取用户宠物列表错误:', error);
    return next(new AppError('获取宠物列表失败', 500));
  }
};

// 获取所有宠物（管理员功能）
exports.getAllPets = async (req, res, next) => {
  try {
    const where = {};
    
    // 物种过滤
    if (req.query.species) {
      where.species = req.query.species;
    }
    
    // 状态过滤
    if (req.query.status) {
      where.status = req.query.status;
    }
    
    // 主人过滤
    if (req.query.ownerId) {
      where.ownerId = req.query.ownerId;
    }
    
    // 分页
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    // 排序
    const order = [];
    if (req.query.sort) {
      const sortFields = req.query.sort.split(',');
      sortFields.forEach(field => {
        if (field.startsWith('-')) {
          order.push([field.substring(1), 'DESC']);
        } else {
          order.push([field, 'ASC']);
        }
      });
    } else {
      order.push(['createdAt', 'DESC']);
    }
    
    const { count, rows: pets } = await Pet.findAndCountAll({
      where,
      order,
      limit,
      offset,
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'email']
      }]
    });
    
    res.status(200).json({
      status: 'success',
      results: pets.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        pets
      }
    });
  } catch (error) {
    logger.error('获取宠物列表错误:', error);
    return next(new AppError('获取宠物列表失败', 500));
  }
};

// 获取单个宠物信息
exports.getPet = async (req, res, next) => {
  try {
    const pet = await Pet.findByPk(req.params.id, {
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'email', 'phone']
      }]
    });
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限：只有宠物主人、管理员或护理员可以查看
    if (req.user.role !== 'admin' && 
        pet.ownerId !== req.user.id &&
        req.user.role !== 'caregiver') {
      return next(new AppError('您没有权限查看此宠物信息', 403));
    }
    
    res.status(200).json({
      status: 'success',
      data: {
        pet
      }
    });
  } catch (error) {
    logger.error('获取宠物信息错误:', error);
    return next(new AppError('获取宠物信息失败', 500));
  }
};

// 创建新宠物
exports.createPet = async (req, res, next) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    // 设置宠物主人为当前用户
    req.body.ownerId = req.user.id;
    
    const newPet = await Pet.create(req.body);
    
    // 填充关联数据
    await newPet.reload({
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'email']
      }]
    });
    
    logger.info(`用户创建宠物: ${req.user.email} - ${newPet.name}`);
    
    res.status(201).json({
      status: 'success',
      message: '宠物信息创建成功',
      data: {
        pet: newPet
      }
    });
  } catch (error) {
    logger.error('创建宠物错误:', error);
    return next(new AppError('创建宠物失败', 500));
  }
};

// 更新宠物信息
exports.updatePet = async (req, res, next) => {
  try {
    // 检查验证错误
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return next(new AppError('输入数据验证失败', 400));
    }
    
    const pet = await Pet.findByPk(req.params.id);
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限：只有宠物主人或管理员可以更新
    if (req.user.role !== 'admin' && pet.ownerId !== req.user.id) {
      return next(new AppError('您没有权限更新此宠物信息', 403));
    }
    
    // 过滤不允许更新的字段
    const filteredBody = filterObj(
      req.body,
      'name',
      'species',
      'breed',
      'gender',
      'dateOfBirth',
      'color',
      'size',
      'weight',
      'photos',
      'health',
      'behavior',
      'feeding',
      'careNeeds',
      'emergencyContact',
      'status',
      'availability'
    );
    
    await pet.update(filteredBody);
    
    await pet.reload({
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'email']
      }]
    });
    
    logger.info(`宠物信息更新: ${pet.name} - ${req.user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '宠物信息更新成功',
      data: {
        pet
      }
    });
  } catch (error) {
    logger.error('更新宠物信息错误:', error);
    return next(new AppError('更新宠物信息失败', 500));
  }
};

// 删除宠物
exports.deletePet = async (req, res, next) => {
  try {
    const pet = await Pet.findByPk(req.params.id);
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限：只有宠物主人或管理员可以删除
    if (req.user.role !== 'admin' && pet.ownerId !== req.user.id) {
      return next(new AppError('您没有权限删除此宠物', 403));
    }
    
    // TODO: 检查是否有进行中的订单
    // const { Order } = require('../models');
    // const activeOrders = await Order.count({
    //   where: {
    //     petId: pet.id,
    //     status: { [Op.in]: ['pending', 'confirmed', 'in_progress'] }
    //   }
    // });
    // 
    // if (activeOrders > 0) {
    //   return next(new AppError('该宠物有进行中的订单，无法删除', 400));
    // }
    
    await pet.destroy();
    
    logger.info(`宠物删除: ${pet.name} - ${req.user.email}`);
    
    res.status(204).json({
      status: 'success',
      message: '宠物删除成功',
      data: null
    });
  } catch (error) {
    logger.error('删除宠物错误:', error);
    return next(new AppError('删除宠物失败', 500));
  }
};

// 搜索宠物
exports.searchPets = async (req, res, next) => {
  try {
    const { q, species, breed, size, location, needsCare } = req.query;
    
    // 构建搜索条件
    const where = {};
    const orConditions = [];
    
    if (q && q.length >= 2) {
      orConditions.push(
        { name: { [Op.like]: `%${q}%` } },
        { breed: { [Op.like]: `%${q}%` } }
      );
    }
    
    if (orConditions.length > 0) {
      where[Op.or] = orConditions;
    }
    
    // 添加过滤条件
    if (species) where.species = species;
    if (breed) where.breed = { [Op.like]: `%${breed}%` };
    if (size) where.size = size;
    
    // TODO: 地理位置搜索（如果提供了坐标）
    
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const offset = (page - 1) * limit;
    
    const { count, rows: pets } = await Pet.findAndCountAll({
      where,
      include: [{
        model: User,
        as: 'owner',
        attributes: ['id', 'firstName', 'lastName', 'address']
      }],
      order: [['createdAt', 'DESC']],
      limit,
      offset
    });
    
    res.status(200).json({
      status: 'success',
      results: pets.length,
      total: count,
      page,
      totalPages: Math.ceil(count / limit),
      data: {
        pets
      }
    });
  } catch (error) {
    logger.error('搜索宠物错误:', error);
    return next(new AppError('搜索宠物失败', 500));
  }
};

// 上传宠物照片
exports.uploadPetPhotos = async (req, res, next) => {
  try {
    if (!req.files || req.files.length === 0) {
      return next(new AppError('请选择要上传的图片', 400));
    }
    
    const pet = await Pet.findByPk(req.params.id);
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限
    if (req.user.role !== 'admin' && pet.ownerId !== req.user.id) {
      return next(new AppError('您没有权限上传此宠物的照片', 403));
    }
    
    // TODO: 实现文件上传逻辑（如上传到云存储）
    const photoUrls = req.files.map(file => `/uploads/pets/${file.filename}`);
    
    // 添加新照片到现有照片列表
    const currentPhotos = pet.photos || [];
    await pet.update({ photos: [...currentPhotos, ...photoUrls] });
    
    logger.info(`宠物照片上传: ${pet.name} - ${req.user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '照片上传成功',
      data: {
        pet,
        uploadedPhotos: photoUrls
      }
    });
  } catch (error) {
    logger.error('上传宠物照片错误:', error);
    return next(new AppError('上传照片失败', 500));
  }
};

// 删除宠物照片
exports.deletePetPhoto = async (req, res, next) => {
  try {
    const { photoUrl } = req.body;
    
    if (!photoUrl) {
      return next(new AppError('请提供要删除的照片URL', 400));
    }
    
    const pet = await Pet.findByPk(req.params.id);
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限
    if (req.user.role !== 'admin' && pet.ownerId !== req.user.id) {
      return next(new AppError('您没有权限删除此宠物的照片', 403));
    }
    
    // 从照片列表中移除指定照片
    const currentPhotos = pet.photos || [];
    const updatedPhotos = currentPhotos.filter(photo => photo !== photoUrl);
    await pet.update({ photos: updatedPhotos });
    
    // TODO: 删除实际的文件
    
    logger.info(`宠物照片删除: ${pet.name} - ${req.user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '照片删除成功',
      data: {
        pet
      }
    });
  } catch (error) {
    logger.error('删除宠物照片错误:', error);
    return next(new AppError('删除照片失败', 500));
  }
};

// 获取宠物统计信息
exports.getPetStats = async (req, res, next) => {
  try {
    const { sequelize } = require('../config/database');
    
    const totalPets = await Pet.count();
    const activePets = await Pet.count({ where: { status: 'active' } });
    
    // 按物种统计
    const speciesStats = await Pet.findAll({
      attributes: [
        'species',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['species'],
      order: [[sequelize.literal('count'), 'DESC']]
    });
    
    // 按大小统计
    const sizeStats = await Pet.findAll({
      attributes: [
        'size',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      group: ['size']
    });
    
    res.status(200).json({
      status: 'success',
      data: {
        overview: {
          totalPets,
          activePets,
          inactivePets: totalPets - activePets
        },
        speciesDistribution: speciesStats,
        sizeDistribution: sizeStats
      }
    });
  } catch (error) {
    logger.error('获取宠物统计错误:', error);
    return next(new AppError('获取统计信息失败', 500));
  }
};

// 更新宠物健康信息
exports.updatePetHealth = async (req, res, next) => {
  try {
    const pet = await Pet.findByPk(req.params.id);
    
    if (!pet) {
      return next(new AppError('未找到该宠物', 404));
    }
    
    // 检查权限
    if (req.user.role !== 'admin' && pet.ownerId !== req.user.id) {
      return next(new AppError('您没有权限更新此宠物的健康信息', 403));
    }
    
    // 更新健康信息
    const healthUpdate = filterObj(
      req.body,
      'vaccinations',
      'spayedNeutered',
      'allergies',
      'medications',
      'medicalConditions',
      'veterinarianVisits'
    );
    
    const currentHealth = pet.health || {};
    const updatedHealth = { ...currentHealth, ...healthUpdate };
    
    await pet.update({ health: updatedHealth });
    
    logger.info(`宠物健康信息更新: ${pet.name} - ${req.user.email}`);
    
    res.status(200).json({
      status: 'success',
      message: '健康信息更新成功',
      data: {
        pet
      }
    });
  } catch (error) {
    logger.error('更新宠物健康信息错误:', error);
    return next(new AppError('更新健康信息失败', 500));
  }
};